const BaseIpcHandler = require('../BaseIpcHandler');
const { Pipeline } = require('../../pipeline/engine/index');
const path = require('path');

class PipelineStartHandler extends BaseIpcHandler {
    // 发送异步消息到队列，方便客户端获取信息
    publish(jobId, event, data) {
        this.app &&
            this.app.queue.enqueue(
                `pipeline:${jobId}`,
                {
                    event: event,
                    data: data
                },
                false
            );
    }

    async handle(event, params) {
        // 解析参数
        console.log(`>> PipelineStartHandler params = `, params);
        const { jobId, pipeline, batch, inputs } = params;

        // 业务逻辑
        let result = null;
        try {
            // 临时测试pipeline功能
            const pipe = new Pipeline(this.app);
            pipe.on('failed', (error) => {
                // console.log('==> Pipeline execution failed:', error);
                this.publish(jobId, 'pipeline_error', error);
            });
            pipe.on('percent', (percent) => {
                // console.log('==> Pipeline execution percent:', percent);
                this.publish(jobId, 'pipeline_percent', percent);
            });
            pipe.on('done', (result) => {
                // console.log('==> Pipeline batch execution done:', result);
                this.publish(jobId, 'pipeline_result', result);
            });

            // 测试detection节点
            const pipe_conf_root = path.resolve(__dirname, '../../pipeline/engine/configs');
            const pipe_path = path.join(pipe_conf_root, pipeline.config);
            const pipe_conf = require(pipe_path);

            // const { imageToBase64 } = require('./imageUtils.js');
            // const file_path = '/home/lixiang/data/psdvideos/frames/FEE_71261370e3b3d9446_85_0_1739768266442_2_0_v1.0.1_20250214160148_frame0012.jpg';
            pipe.loadConfig(pipe_path, pipe_conf);
            if (batch) {
                pipe.runBatch(inputs, `pipeline:${jobId}`);
            } else {
                pipe.run(inputs);
            }
            result = { code: 0, msg: `Pipeline ${pipeline.name} Started OK!` };
        } catch (error) {
            result = { code: -1, msg: error.message };
        }

        // 返回结果
        // console.log(`PipelineStartHandler result = `, result);
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = PipelineStartHandler;
